<template>
  <div>
    <el-card>
      <SearchItem :searchTitle @search="searchRole"></SearchItem>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
      <el-table border :data="roleData" style="margin: 20px 0">
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="职位名字" align="center" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="User" @click="setPermission(row)"
              >分配权限</el-button
            >
            <el-button type="primary" size="small" icon="Edit" @click="updateRole(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`你确定要删除${row.roleName}?`"
              width="260px"
              @confirm="deleteRole(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next, jumper,->,sizes,total"
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[8, 12, 16, 20]"
        @current-change="getHasRole"
        @size-change="getHasRole"
      />
    </el-card>
    <el-dialog v-model="dialogFormVisible" width="500">
      <template #header>
        {{ roleForm.id ? '编辑职称：' : '添加职称：' }}
      </template>
      <el-form :model="roleForm" :rules="rules" ref="form">
        <el-form-item label="职位名称：">
          <el-input v-model="roleForm.roleName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中 ...' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="drawerVisible">
      <template #header>
        <h4>分配菜单与按钮权限</h4>
      </template>
      <template #default>
        <!-- 树形控件 -->
        <el-tree
          ref="tree"
          :data="menuArr"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectArr"
          :default-expanded-keys="selectArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { reqAllMenuList, reqAllRoleList } from '@/api/acl/role'
import type { RoleData, MenuList } from '@/api/acl/role/type'
import { reactive, toRefs, ref, onMounted, nextTick, useTemplateRef } from 'vue'
let searchTitle = '职位'
const searchRole = (word: string) => {
  keyword.value = word
  getHasRole()
}

onMounted(() => {
  getHasRole()
})

let pageNo = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>(0)
let keyword = ref('')
let roleData = ref()
const getHasRole = async () => {
  let res = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value)
  if (res.code === 200) {
    roleData.value = res.data.records
    total.value = res.data.total
  }
}

let dialogFormVisible = ref(false)
let roleForm = reactive<RoleData>({
  roleName: '',
})
let loading = false
let form = ref<any>()
const addRole = () => {
  dialogFormVisible.value = true
  Object.assign(roleForm, { id: 0, roleName: '' })
  nextTick(() => {
    form.value.clearValidate()
  })
}

const updateRole = (row: RoleData) => {
  dialogFormVisible.value = true
  Object.assign(roleForm, row)
  nextTick(() => {
    form.value.clearValidate()
  })
}

const onClick = async () => {
  await form.value.validate()
  console.log(roleForm)
}

let tree = useTemplateRef('tree')
let drawerVisible = ref(false)
let menuArr = ref<MenuList>()
let selectArr = ref<number[]>([])
const defaultProps = {
  children: 'children',
  label: 'name',
}
const setPermission = async (row: RoleData) => {
  drawerVisible.value = true
  let res = await reqAllMenuList(row.id as number)
  if (res.code === 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}

const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select === true && item.children.length === 0) {
      initArr.push(item.id)
    } else if (item.select === true && item.children.length >= 1) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}

const handler = () => {}

const deleteRole = (roleId: string) => {}

//自定义校验规则的回调
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}
//职位校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
</script>
<style scoped lang="scss"></style>
